using UnityEngine;
using System.Collections;

public class InstanceManager : MonoBehaviour 
{
	public Transform tower;
	public int money;
	private Transform towerAvatar;
	private BlockManager lastBlock;
	private bool isClear = false;
	private bool inBoard = false;
	private bool hasObject = false;
	void Update()
	{
		Ray ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition);
		RaycastHit hit;
		
		if(Physics.Raycast(ray,out hit,Mathf.Infinity))
		{
			if(hasObject)
			{
				if(hit.collider.tag == "Grass")
				{	
					inBoard = true;
					lastBlock = hit.transform.GetComponent<BlockManager>();
				
					if(!lastBlock.isFree)
					{
						if(towerAvatar)	
						{
							Destroy(towerAvatar.gameObject);	
						}
					
						Vector3 towerPos = hit.transform.position;
						towerPos.z = 4.211397f;
						towerAvatar = Instantiate(tower,towerPos,tower.rotation) as Transform;
						towerAvatar.name = "Tower Avatar";
						Color towerColor = towerAvatar.renderer.material.color;
						towerColor.a = 0.3f;
						towerAvatar.renderer.material.color = towerColor;
					}
					else
					{
						if(!isClear)
						{	
							if(towerAvatar)	
							{
								Destroy(towerAvatar.gameObject);	
							}
						}
						else
						{
							Color towerColor = lastBlock.tower.renderer.material.color;
							towerColor.a = 1;
							lastBlock.tower.renderer.material.color = towerColor;
						}
					}
				}
			
				else
				{
					//Color towerColor = lastBlock.tower.renderer.material.color;
					//towerColor.a = 1;
					//	lastBlock.tower.renderer.material.color = towerColor;
				}
			}
			
			if(hit.collider.name == "Clear")
			{
				inBoard = false;
				if(towerAvatar)	
				{
					Destroy(towerAvatar.gameObject);	
				}
			}
								

		}
		
		else
		{
			inBoard = false;
			if(towerAvatar)	
			{
				Destroy(towerAvatar.gameObject);	
			}
		}
		
		
		if(Input.GetButtonDown("Fire1"))
		{
			if(Physics.Raycast(ray,out hit,Mathf.Infinity))
			{
				if(hit.collider.name == "Clear")
				{
					isClear = !isClear;
				}
				
				if(hit.collider.tag == "Tower")
				{
					if(hit.collider.gameObject.GetComponent<TowerInfo>().price < money)
					{
						money -= hit.collider.gameObject.GetComponent<TowerInfo>().price;
						tower = hit.collider.gameObject.GetComponent<TowerInfo>().towerPrefab;
						hasObject = true;
						Debug.Log("buy");
					}
				}
			}
			
			if(inBoard)
			{
				if(!isClear)
				{
					if(towerAvatar)
					{
						Color towerColor = towerAvatar.renderer.material.color;
						towerColor.a = 1f;
						towerAvatar.renderer.material.color = towerColor;
						lastBlock.isFree = false;
						lastBlock.tower = towerAvatar;
						towerAvatar.name = tower.name;
						towerAvatar = null;
						lastBlock = null;
						tower = null;
						hasObject = false;
					}
				
				}
				else
				{
					if(!lastBlock.isFree)
					{
						Destroy(lastBlock.tower.gameObject);
						lastBlock.isFree = true;
						isClear = false;
					}
				}
			}
		}
		

	}
}
